﻿using System;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.Web.Mvc;
using Web.Auction.Bid.Models;
using System.Collections.Generic;
using Web.Auction.Bid.Extensions;
using Newtonsoft.Json.Converters;

namespace Web.Auction.Bid.Controllers
{
    public class HomeController : Controller
    {
        private readonly AuctionManager manager;

        public HomeController()
            : this(AuctionManager.Instance)
        {

        }

        public HomeController(AuctionManager manager)
        {
            this.manager = manager;
        }

        public ActionResult Index()
        {
            var now = DateTime.Now;
            if (manager.CheckTime(now) && manager.MarketState != MarketState.Open)
            {
                manager.OpenMarket();
            }
            if ((now.Hour < manager.OpenTime.Hour) && manager.MarketState != MarketState.Closed)
            {
                manager.CloseMarket();
            }
            var model = new HomeControllerModel.Index();

            int seconds;
            var auctions = new List<Models.Auction>();
            var opened = manager.CheckTime(now);

            var closeTime = manager.CloseTime;

            var tomorrow = HttpContext.Cache.Put("TomorrowAuctions", closeTime, () => manager.GetTomorrowAuctions());

            if (opened)
            {
                //var closed = manager.GetClosedAuctions();

                //auctions.AddRange(closed);

                seconds = (int)closeTime.Subtract(now).TotalSeconds;

                var today = manager.Auctions.OrderBy(o => o.Status)
                    .ThenBy(o => o.StartDateTime).ThenByDescending(o => o.Grade);

                model.JsonData = GetJsonData(today);

                auctions.AddRange(today);
                auctions.AddRange(tomorrow);
            }
            else
            {
                var openTime = manager.OpenTime;
                seconds = (int)openTime.Subtract(now).TotalSeconds;

                var today = HttpContext.Cache.Put("TodayAuctions", openTime, manager.GetTodayAuctions);

                auctions.AddRange(today);

                auctions.AddRange(tomorrow);
            }

            model.Opened = opened;
            model.Seconds = seconds;
            model.Auctions = auctions;
            model.Identity = User.Identity.Identity();
            return View(model);
        }

        public ActionResult Bid(int param)
        {
            var now = DateTime.Now;
            var result = new SkResult<object>();
            var identity = User.Identity.Identity();
            if (!Request.IsAuthenticated)
            {
                result.Message = "请先登录！";
                return Json(result);
            }
            if (!manager.CheckTime(now))
            {
                result.Message = "未到竞拍时间！";
                return Json(result);
            }
            var ipaddress = GetClientIp();
            result = manager.Bid(param, identity.Id, User.Identity.Name, identity.NickName, ipaddress);
            return Json(result);
        }

        private string GetClientIp()
        {
            var result = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = Request.ServerVariables["REMOTE_ADDR"];
            }
            return result;
        }

        private static IHtmlString GetJsonData(IEnumerable<Models.Auction> auctions)
        {
            var data = auctions.ToDictionary(o => o.Id, o => new {
                o.Interval,
                o.Counter,
                Price = o.BidPrice,
                o.UserId, o.NickName,
                OpenTime = o.StartDateTime,
                CloseTime = o.StopDateTime,
                OfflineTime = o.TransactionTime.HasValue ? o.TransactionTime.Value.AddMinutes(3) : o.StopDateTime, o.Status
            });
            return new MvcHtmlString(JsonConvert.SerializeObject(data, new JavaScriptDateTimeConverter()));
        }
    }
}
